import rowingmanager.domain.Organization
import rowingmanager.domain.Address
import util.groovy.captcha.Captcha
import rowingmanager.domain.Rower
import rowingmanager.domain.Country
import util.groovy.command.RowerCreateCommand
import rowingmanager.domain.JsecRole
import rowingmanager.domain.JsecUserRoleRel
import org.springframework.web.multipart.MultipartFile

class RowerController {
   def fileService 
   def registerRower = {
      def captcha = new Captcha()
      session.captcha = captcha
      log.info("Generated captcha with result ${captcha?.result}")

     return [rower:new Rower(),clist:Country.list()]
   }

  def saveRower = {  RowerCreateCommand cmd ->
       log.info("PARAMS:"+params.inspect())
      def c = (session?.captcha?.result.toString() == params?.captchaValue)
        log.debug("c returns ${c} | captcha from session: ${session?.captcha?.result.toString()} | captcha from request: ${params?.captchaValue}")

      if(!cmd.hasErrors() && c){
         log.info("validates!")
         def newRower = cmd.createRower()
         Organization organization
         if(params.individual == 'on'){
           // dodas novega rowerja v "Individual" organizacijo
           Address dummyAddress
           log.info("Rower is an individual")  // tole vspodaj je dokaz , da moram dati tudi validacijo organizacij v command object
           organization = Organization.findByTitle("individual")
           dummyAddress = new Address(street:'blabla',state:'blalba',city:'blabla',postalCode:'blalba',country:Country.get(params.country))
           if(!organization){
           organization = new Organization(title:'individual',phone:'88888',address:dummyAddress)
           log.info("Creating new organization for individuals ")
           organization.save()
           }
         }
         else{
          //rower belongs to an actual organization
           if(params.organization != ''){
              log.info("Rower belongs to a club")
              newRower.address.country = Country.get(params.country)
              organization = Organization.get(params.club)
           }
           else{
              render 'select organization!'
           }
         }
         newRower.organization = organization
         def rowerRole = JsecRole.findByName("Rower")
         if(!rowerRole){
          log.info("Creating role - Rower")
          rowerRole = new JsecRole(name:"Rower")
          rowerRole.save()
         }

        MultipartFile file = request.getFile('logoInput');
        if(!file.isEmpty())
            newRower.avatar = fileService.uploadAndGetImage(file,newRower.email)
        else
            log.info("No picture specified...skipping resize")

         if(newRower.save()){
           new JsecUserRoleRel(user:newRower,role:rowerRole).save()
           render 'success we saved it'
         }
         else{
           render(view:'registerRower',model:[rower:newRower,clist:Country.list()])
         }

      }
      else {
        println cmd.errors.each {println it }
        flash.captcha = 'Incorrect value'
        render(view:'registerRower',model:[rower:cmd,clist:Country.list()])
      }

  }

   def findClubsByCountry = {
     log.info(params.inspect())
    def country = Country.get(params['id'])
    def clubs = Organization.withCriteria{
        eq('type','rowing club')
        address {
          eq('country',country)
        }
     }

     log.info("Size of clubs found : "+clubs.size())
     if(clubs.size() > 0)
        render g.select(optionKey: 'id', from:clubs, id: 'club', name: "club")
     else if(clubs.size() == 0)
        render '''<span style="color:red;">There are no rowing clubs registered for selected country!</span> '''   
    

   }

  def checkCaptcha = {
    println("checking captcha..")
    println  params.inspect()
    println "result is "+ session?.captcha?.result
    if(session?.captcha?.result.toString() == params?.captchaValue)
      render '''<img src="/RowingManagement/icons/green_check.jpg" alt="correct"/> '''
    else
      render '''<img src="/RowingManagement/icons/red_cross.png" alt="wrong!"/> '''
  }
}
